package cn.aopmin.java.api.lang;

/**
 * 线程安全问题测试用例
 * @author 白豆五
 * @since 2025/1/29
 */
public class ThreadNotSafeTest {
    public static void main(String[] args) {

        // 创建售票任务对象
        TicketWindow ticketWindow = new TicketWindow();

        // 模拟4个窗口
        Thread window1 = new Thread(ticketWindow, "窗口1：");
        Thread window2 = new Thread(ticketWindow, "窗口2：");
        Thread window3 = new Thread(ticketWindow, "窗口3：");
        Thread window4 = new Thread(ticketWindow, "窗口4：");

        window1.start();
        window2.start();
        window3.start();
        window4.start();

    }
}

/**
 * 售票任务
 */
class TicketWindow implements Runnable {

    /**
     *  100张票，共享变量， 由4个线程共享
     */
    int ticket = 100;

    /**
     * 售票, 没有考虑线程安全问题
     */
    @Override
    public void run() {
        while (ticket > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String msg = String.format("%s正在出售第%s张票", Thread.currentThread().getName(), ticket);
            System.out.println(msg);
            ticket--;
        }
    }
}